package project.active;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Scanner;

import model.pojo.Employee;
import model.pojo.Languages;
import nguyen.dao.LoginSystem;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import approval.dao.AcEliManagerDAO;
import approval.dao.LangDAO;
import approve.action.MainFrame;
import approve.action.R;

public class LogoutActivity extends Activity{
	EditText username;
	EditText pass,dbname;
//	Spinner spLangs;
	private Bundle alllangs = new Bundle();
	String typeLang = "EN",database;
	private boolean read = true;
	AcEliManagerDAO acelidao= new AcEliManagerDAO();
	//TODO hongmophi
	private String userName,password,dbn;
	Employee emp;
	ImageView imageVN,imageEN,imageKR;

	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		initAttribute();
//		initLang();
		Button btLogin = (Button) findViewById(R.id.btLogin);
		dbname=(EditText)findViewById(R.id.tv_dbname);
		username = (EditText) findViewById(R.id.userName);
		pass = (EditText) findViewById(R.id.pass);

		
		imageVN = (ImageView)findViewById(R.id.imageViewVN);
		imageEN = (ImageView)findViewById(R.id.imageViewUK);
		imageKR = (ImageView)findViewById(R.id.imageViewKR);
		
		imageVN.setOnClickListener(processImageVN);
		imageEN.setOnClickListener(processImageEN);
		imageKR.setOnClickListener(processImageKR);
		
		btLogin.setOnClickListener(loginbtn);
		
		readFile();
		
		final CheckBox rememberMeCbx = (CheckBox)findViewById(R.id.checkRemember);
		rememberMeCbx.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				 if (((CheckBox) v).isChecked()) {
					 System.out.println(" boolean check : " + ((CheckBox) v).isChecked());
					 try {
					 userName = username.getText().toString();
					 password = pass.getText().toString();
					 dbn=dbname.getText().toString();
					 if(!username.equals("") && !password.equals("") && !dbn.equals("")){
						 System.out.println("Last username :" + userName);
						 System.out.println("Last password : " + password);
//						 	File f = new File("user.txt");
							FileOutputStream file = openFileOutput("user.txt", Context.MODE_PRIVATE);
							file.write(dbn.getBytes());
							file.write("-".getBytes());
							file.write(userName.getBytes());
							file.write("-".getBytes());
							MessageDigest ms = MessageDigest.getInstance("MD5");
							byte[] enpas =ms.digest(password.getBytes());
							file.write(password.getBytes());
							file.close();
					 }
						} catch (NoSuchAlgorithmException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
					 
				 }else{
					 try {
						 System.out.println("Not check remember ++++++++++++++++++++++++++++++");
						 File file = new File("user.txt");
						 file.delete();
						 File newFile = new File("user.txt");
						 newFile.createNewFile();
						 
					} catch (Exception e) {
						e.printStackTrace();
					}
					 
				 }
			}
		});
		
		
		
		
	}
	private OnClickListener loginbtn = new OnClickListener() {
		

		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(acelidao.checkexitdb(dbname.getText().toString())==true){
				database=dbname.getText().toString();
				emp = checkLogin(username.getText().toString(), pass.getText().toString());
				if (emp != null) {
					startActivity(emp);
				} else {
					openDialogError();
				}
			}else{
				openDialogNoDB();
			}
			
			
		}
	}; 
	
	private void startActivity(Employee em) {
		Intent i = new Intent(this, MainFrame.class);
		i.putExtra("database", database);
		i.putExtra("lang", typeLang);
		i.putExtras(alllangs);
		i.putExtra("em", em);
		startActivity(i);
	}
	private void openDialogError() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		Bundle lang = this.getAlllangs().getBundle(typeLang);
		builder.setTitle("Warning");
		builder.setMessage(lang.getString("ac_tb_UserOrPassNotCorrect"));
		builder.setCancelable(false);
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		builder.show();
	}
	
	private void openDialogNoDB() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		Bundle lang = this.getAlllangs().getBundle(typeLang);
		builder.setTitle("Warning");
		builder.setMessage(lang.getString("ac_CSDLKhongTonTai"));
		builder.setCancelable(false);
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		builder.show();
	}
	
	public void setDatabase(String database) {
		this.database = database;
	}
	public Employee checkLogin(String username, String pass) {
		LoginSystem lg = new LoginSystem();
		Employee emp = lg.checkLogin(username, pass,getDatabase());
		return emp;
	}
	public String getDatabase() {
//		Bundle extras = getIntent().getExtras();
//		database = extras.getString("database");
		return database;
	}
	public void initAttribute() {
		Bundle lang = this.getAlllangs().getBundle(typeLang);
		TextView lbdbname=(TextView) findViewById(R.id.lb_dbname);
		lbdbname.setText(lang.getString("ac_ma_DatabaseName"));
		TextView t = (TextView) findViewById(R.id.tendn);
		t.setText(lang.getString("ac_ma_UserName"));
		TextView t2 = (TextView) findViewById(R.id.matkhau);
		t2.setText(lang.getString("ac_ma_Password"));
		Button bt = (Button) findViewById(R.id.btLogin);
		bt.setText(lang.getString("ac_login"));
	}
	
	// image language
	public OnClickListener processImageVN = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			typeLang = "VN";
			initAttribute();
		}
	};
	
	public OnClickListener processImageEN = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			typeLang = "EN";
			initAttribute();
		}
	};
	
	public OnClickListener processImageKR = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			typeLang = "KR";
			initAttribute();
		}
	};
	
//	private void initLang() {
//		String[] langs = new String[] { "Viet Nam", "English", "Korea" };
//		ArrayAdapter<String> arr = new ArrayAdapter<String>(this,
//				android.R.layout.simple_spinner_item, langs);
//		spLangs = (Spinner) findViewById(R.id.cbLang);
//		spLangs.setAdapter(arr);
//		spLangs.setOnItemSelectedListener(spTypeEvent);
//	}
//	private OnItemSelectedListener spTypeEvent = new OnItemSelectedListener() {
//		public void onItemSelected(android.widget.AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//			if (arg2 == 0)
//				typeLang = "VN";
//			if (arg2 == 1)
//				typeLang = "EN";
//			if (arg2 == 2)
//				typeLang = "KR";
//			Log.d(getApplicationContext().getPackageName(), "Select Item :"
//					+ typeLang);
//			initAttribute();
//		}
//
//		public void onNothingSelected(AdapterView<?> arg0) {
//			// TODO Auto-generated method stub
//			Log.d(getApplicationContext().getPackageName(), "Select Item :"
//					+ "Nothing");
//			typeLang = "EN";
//		};
//	};
	public Bundle getAlllangs() {
		if (isRead()) {
			LangDAO lang = new LangDAO();
			Bundle resultVN = new Bundle();
			Bundle resultEN = new Bundle();
			Bundle resultKR = new Bundle();
			try {
				ArrayList<Languages> arr = lang.allLang();
				for (int i = 0; i < arr.size(); i++) {
						resultVN.putString(arr.get(i).getId(), arr.get(i).getVn());
						resultEN.putString(arr.get(i).getId(), arr.get(i).getEn());
						resultKR.putString(arr.get(i).getId(), arr.get(i).getKr());
					};

			} catch (Exception E) {
				E.printStackTrace();
			}
			alllangs.putBundle("VN", resultVN);
			alllangs.putBundle("EN", resultEN);
			alllangs.putBundle("KR", resultKR);
		}
		setRead(false);
		return alllangs;
	}
	public boolean isRead() {
		return read;
	}
	public void setRead(boolean read) {
		this.read = read;
	}
	
private void readFile(){
		
		try {
			FileInputStream fr = openFileInput("user.txt");
			Scanner scanner = new Scanner(fr);
			scanner.useDelimiter("-");
			dbname.setText(scanner.next().trim());
			username.setText(scanner.next().trim());
			pass.setText(scanner.next().trim());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}

}
